package ece452.ims.client;

import java.io.*;
import java.net.*;
import java.util.*;

public class User {

	private static final String HOST = "192.168.3.121";
	private static final int PORT = 21000;
	private static final String nl = "\n";
	private static Socket echoSocket;
	private static PrintWriter out;
	private static BufferedReader in;
	private static User user = null;
	private String username;
	private String password;
	private List<Friend> friendsList;
	public Friend currentFriend; 
	//private static BufferedReader stdin;	
	
	private User(){
		// ...
	}
	
	private void init(){
		try{
			friendsList = new ArrayList<Friend>();
			echoSocket = new Socket(HOST,PORT);
			in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
			//System.out.println("Welcome to IMS Server!");
			//stdin = new BufferedReader(new InputStreamReader(System.in));
			out = new PrintWriter(echoSocket.getOutputStream(), true);
			in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
		}catch (UnknownHostException e){
			System.err.println("Cannot ping destination host.");
			System.err.println("Server must not be available.");
			System.exit(1);
		}catch (IOException e){
			System.err.println("Cound not get I/O for host.");
			System.exit(1);
		}
	}
	
	public static User getInstance(){
		if(user == null) user = new User();
		return user;
	}
	
	public class SendResponse extends Thread{
		
		public void run(){ try{tx();}catch(IOException e){} }
		
		public synchronized void tx() throws IOException{
			//String userInput;
			//BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
			while(true){
				BufferedReader toSend = new BufferedReader(new InputStreamReader(System.in));
				if(userInput.equals("login")){
					out.println();
				}else if(userInput.equals("send")){
					String cfn = currentFriend.getUsername();
					String cfm = currentFriend.getSendMsg();
					out.println("2`"+cfn+"`"+cfm+nl);
				}else{
					System.out.println("all other");
					out.println(userInput+nl);
				}
			}
		}
		
		public synchronized String sendMessage(String uname, String message){
			uname = uname.trim();
			message = message.trim();
			return "2`"+uname+"`"+message+nl;
		}
	}
	
	public class GetResponse extends Thread{
		public void run(){ rx(); }
		public synchronized void rx(){
			while(true){
				try{
					String servReply = in.readLine();
					System.out.println("reply: " + servReply);
				}catch(Exception e){ }
			}
		}
		
		public synchronized void showList(){
			
		}
	}
	
	public static void main(String[] fargs){
		//User foo = null; 
		User foo = User.getInstance();
		SendResponse x = foo.new SendResponse();//.start();
		x.sendMessage(uname, message);
		foo.new GetResponse().start();
	}
	
}
